package com.bitejiuyeke.job_publish.service.impl;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.common.PageResult;
import com.bitejiuyeke.job_publish.common.ResultCode;
import com.bitejiuyeke.job_publish.dao.FavoriteRecordMapper;
import com.bitejiuyeke.job_publish.enums.DeleteStateEnum;
import com.bitejiuyeke.job_publish.enums.JobStateEnum;
import com.bitejiuyeke.job_publish.enums.StateEnum;
import com.bitejiuyeke.job_publish.exception.ApplicationException;
import com.bitejiuyeke.job_publish.model.FavoriteRecord;
import com.bitejiuyeke.job_publish.model.Job;
import com.bitejiuyeke.job_publish.model.User;
import com.bitejiuyeke.job_publish.service.IFavoriteRecordService;
import com.bitejiuyeke.job_publish.service.IJobService;
import com.bitejiuyeke.job_publish.service.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author 比特就业课
 */
@Slf4j
@Service
public class FavoriteRecordServiceImpl implements IFavoriteRecordService {

    @Resource
    private FavoriteRecordMapper mapper;
    @Resource
    private IUserService userService;
    @Resource
    private IJobService jobService;

    @Override
    public void create(FavoriteRecord record) {
        // 校验
        if (record == null || record.getUserId() == null || record.getUserId() <= 0
                || record.getJobId() == null || record.getJobId() <= 0) {
            log.warn("添加收藏失败. " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 是否存在
        FavoriteRecord existRecord = selectNormalByUserIdAndJobId(record.getUserId(), record.getJobId());
        if (existRecord != null) {
            log.warn("添加收藏失败, 已有记录. " + ResultCode.FAILED_CREATE);
            throw new ApplicationException(AppResult.failed("已经添加过收藏"));
        }

        // 校验用户是否正常
        User user = userService.selectById(record.getUserId());
        if (user == null) {
            log.warn("添加收藏失败. " + ResultCode.FAILED_USER_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 校验职位是否正常
        Job job = jobService.selectById(record.getJobId());
        if (job == null) {
            log.warn("添加收藏失败. " + ResultCode.FAILED_JOB_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_JOB_NOT_EXISTS));
        }
        if (JobStateEnum.valueOf(job.getState()) != JobStateEnum.RELEASED) {
            log.warn("添加收藏失败. " + ResultCode.FAILED_JOB_NOT_RELEASED);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_JOB_NOT_RELEASED));
        }
        // 写入记录
        record.setState((byte) StateEnum.NORMAL.getCode());
        record.setDeleteState((byte) DeleteStateEnum.NORMAL.getCode());
        Date now = new Date();
        record.setCreateTime(now);
        record.setUpdateTime(now);
        int row = mapper.insertSelective(record);
        if (row != 1) {
            log.warn("添加收藏失败. " + ResultCode.ERROR_SERVICES);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 更新用户收藏数
        userService.addFavoriteCount(record.getUserId(), 1);
        // 更新职位收藏数
        jobService.addFavoriteCount(record.getJobId(), 1);
        log.info("新增收藏成功, userId = {}, jobId = {}.", record.getUserId(), record.getJobId());
    }

    @Override
    public void deleteById(Long id, Long userId) {
        // 校验
        if (id == null || id <= 0 || userId == null || userId <= 0) {
            log.warn("删除收藏失败. " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询收藏记录
        FavoriteRecord existRecord = mapper.selectByPrimaryKey(id);
        if (existRecord == null) {
            log.warn("删除收藏失败. " + ResultCode.FAILED_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        // 校验用户是否正常
        if (existRecord.getUserId() != userId) {
            log.warn("删除收藏失败. " + ResultCode.FAILED_NOT_PERMISSION);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_PERMISSION));
        }
        // 校验职位是否正常
        Job job = jobService.selectById(existRecord.getJobId());
        if (job == null) {
            log.warn("删除收藏失败. " + ResultCode.FAILED_JOB_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_JOB_NOT_EXISTS));
        }
        // 构造删除对象
        FavoriteRecord update = new FavoriteRecord();
        update.setId(id);
        update.setDeleteState((byte) DeleteStateEnum.DELETED.getCode());
        update.setUpdateTime(new Date());
        int row = mapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
            log.warn("删除收藏失败. " + ResultCode.ERROR_SERVICES);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 更新用户收藏数
        userService.minusFavoriteCount(existRecord.getUserId(), 1);
        // 更新职位收藏数
        jobService.minusFavoriteCount(existRecord.getJobId(), 1);
        log.info("删除收藏成功, userId = {}, jobId = {}.", existRecord.getUserId(), existRecord.getJobId());
    }

    @Override
    public FavoriteRecord selectNormalByUserIdAndJobId(Long userId, Long jobId) {
        // 校验
        if (userId == null || userId <= 0 || userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        FavoriteRecord record = new FavoriteRecord();
        record.setUserId(userId);
        record.setJobId(jobId);
        // 查询
        FavoriteRecord result = mapper.selectNormalByUserIdAndJobId(record);
        return result;
    }

    @Override
    public int selectTotalByUser(FavoriteRecord record) {
        // 校验
        if (record == null || record.getPageSize() == null || record.getOffset() == null) {
            log.info("获取用户收藏总数失败. " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询
        int totalRecord = mapper.selectTotalByUser(record);
        return totalRecord;
    }

    @Override
    public PageResult<FavoriteRecord> selectPageByUser(FavoriteRecord record) {
        // 获取总数
        int totalRecord = selectTotalByUser(record);
        // 分页结果对象
        PageResult<FavoriteRecord> pageResult = new PageResult<>(record.getPageNum(), record.getPageSize(),
                totalRecord);
        // 分页数据列表
        List<FavoriteRecord> list = mapper.selectPageByUser(record);
        pageResult.setRows(list);
        // 返回结果
        return pageResult;
    }
}
